/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package infoplaces2;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.imageio.ImageIO;
import javaxt.io.*;
//import principal.Main;

/**
 *
 * @author jonas
 */
public final class Photo {

    private BufferedImage image;
    private double longitude;
    private double latitude;

    public Photo(URL url) throws IOException {
        URLConnection connection = url.openConnection();
        connection.connect();

        File filename = File.createTempFile("infoplaces_", "");

        try (InputStream is = connection.getInputStream()) {
            
            try (FileOutputStream os = new FileOutputStream(filename)) {
                
                int b;
                while ((b = is.read()) != -1) {
                    os.write(b);
                }

            }
        }
        
        init(filename);
    }

    public Photo(File filename) throws IOException {
        init(filename);
    }
    
    public Photo(BufferedImage image, double longitude, double latitude) {
        init(image, longitude, latitude);
    }
    
    private void init(File filename) throws IOException {
        Image imageFile = new Image(filename);
        double[] gps = imageFile.getGPSCoordinate();
        
        if (gps == null) {
            throw new RuntimeException("A imagem informada não possui coordenadas de GPS.");
        }
        
        init(ImageIO.read(filename), gps[0], gps[1]);
    }

    private void init(BufferedImage image, double longitude, double latitude) {
        if (image == null) {
            throw new IllegalArgumentException("Imagem não informada");
        }
        
        this.image = image;        
        this.longitude = longitude;
        this.latitude = latitude;
    }

    public BufferedImage getImage() {
        return image;
    }

    public double getLatitude() {
        return latitude;
    }

    public double getLongitude() {
        return longitude;
    }

}
